package com.whoops.cloud.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

public class CookieFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String uri = request.getRequestURI();
        if (StringUtils.equals(uri,"/security/login")){   //登录请求拦截
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        HttpServletResponse response = requestContext.getResponse();
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies){
            System.out.println("CookieFilter"+cookie.getName());
            if (StringUtils.equals(cookie.getName(),"ZuulToken")){
//                response.addCookie(cookie);
                return null;
            }
        }
        UUID uuid = UUID.randomUUID();
        Cookie cookie = new Cookie("ZuulToken",uuid.toString());
        cookie.setMaxAge(-1);
        cookie.setPath("/");
        response.addCookie(cookie);
        return null;
    }
}
